I fetch data from openweatherAPI by using react-redux Toolkit. I can get name but when I want to get main.temp it gives an error
typeError: Cannot read properties of undefined (reading 'temp')
export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`https://api.openweathermap.org/data/2.5/weather?q=${selectedCity}&appid=6d735f036884219e3a12eeb6f7bf6f93`)
return res.data});
ExtraReducers
[fetchDefault.fulfilled]: (state , action) => {
state.item = action.payload;
console.log(state.item)
},
It works if I return res.data.main but this time cant get name .
index.js
const getCity = useSelector((state) => state.weather.item);
{getCity.main.temp} // Gives Error..
Array looks like this..
{
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
}
],
"main": {
"temp": 300.15,
"pressure": 1007,
"humidity": 74,
"temp_min": 300.15,
"temp_max": 300.15
},
"wind": {
"speed": 3.6,
"deg": 160
"id": 2172797,
"name": "Cairns",
"cod": 200
}
Your reducer saves action.payload into state.item, so I think the useSelector should return state.item.name for getCity (assuming that you want to access the city's name with that selector).
Alternatively, you can create a selector for state.item, and access everything through that.
Btw, your reducer should return a value, so assuming that state was an object initially, it should look like:
[fetchDefault.fulfilled]: (state , action) => {
return {...state, item: action.payload}
},